package com.hengtiansoft.lfy.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.hengtiansoft.lfy.R;
import com.hengtiansoft.lfy.base.BaseActivity;
import com.hengtiansoft.lfy.chart.applib.utils.HXPreferenceUtils;
import com.hengtiansoft.lfy.constants.Constants;
import com.hengtiansoft.lfy.entity.ServiceResult;
import com.hengtiansoft.lfy.net.NetHelper;
import com.hengtiansoft.lfy.net.NetUtils;
import com.hengtiansoft.lfy.utils.Config;
import com.hengtiansoft.lfy.utils.Utils;

import org.json.JSONException;
import org.json.JSONObject;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

/**
 * Created by daiye on 2016/10/27 0027.
 */

public class PasswordForgetActivity extends BaseActivity {
    private static final String TAG = PasswordForgetActivity.class.getSimpleName();
    private ImageView iv_back = null;
    private EditText mUserNameEt;
    private EditText mPasswordEt;
    private EditText mPasswordAgainEt;
    private EditText mVerificationEt;
    private Button mVerificationBt;
    private Button mChangeBt;
    private cn.smssdk.EventHandler eh;
    private Countdown mCountdown = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerSMS();
        initData();
        initView();
    }

    private void registerSMS() {
        SMSSDK.initSDK(this, Constants.SMS_APP_ID, Constants.SMS_APP_KEY);
        eh = new cn.smssdk.EventHandler(){
            @Override
            public void afterEvent(int event, int result, Object data) {

                if (result == SMSSDK.RESULT_COMPLETE) {
                    //回调完成
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        //提交验证码成功
                        Log.i("supeng", data.toString());
                        PasswordForgetActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                changePasswordServer();
                            }
                        });
                    }else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE){
                        PasswordForgetActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //获取验证码成功
                                mCountdown.start();
                            }
                        });

                        Log.i("supeng",data.toString());
                    }else if (event ==SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES){
                        //返回支持发送验证码的国家列表
                        Log.i("supeng",data.toString());
                    }
                }else{
                    ((Throwable)data).printStackTrace();
                    // pd.dismiss();
                    Log.i("supeng",data.toString());
                    try {
                        final JSONObject jsonObject=new JSONObject(((Throwable) data).getMessage().toString());
                        int status= jsonObject.getInt("status");
                        switch (status){

                            default:
                                PasswordForgetActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            Toast.makeText(PasswordForgetActivity.this, jsonObject.getString("description"), Toast.LENGTH_SHORT).show();
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }});
                                break;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        SMSSDK.registerEventHandler(eh); //注册短信回调

    }
    private void initData() {
        mCountdown = new Countdown(60000, 1000);
    }

    private void initView() {
        setContentView(R.layout.activity_passwordforget);
        iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(new View.OnClickListener() {
            public final void onClick(View v) {
                finish();
            }
        });
        mUserNameEt = (EditText) findViewById(R.id.username_et);
        mPasswordEt = (EditText) findViewById(R.id.password_et);
        mPasswordAgainEt = (EditText) findViewById(R.id.password_again_et);
        mVerificationEt = (EditText) findViewById(R.id.verification_et);
        mVerificationBt = (Button)findViewById(R.id.verification_bt);

        mChangeBt = (Button)findViewById(R.id.change_bt);
        mChangeBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager inputManager = (InputMethodManager) mChangeBt.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.showSoftInput(mChangeBt, 0);
                processChange();
            }
        });
        mVerificationBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendIdentifyingCode();
            }
        });

        mPasswordEt.setTypeface(Typeface.DEFAULT);
        mPasswordEt.setTransformationMethod(new PasswordTransformationMethod());
        mPasswordAgainEt.setTypeface(Typeface.DEFAULT);
        mPasswordAgainEt.setTransformationMethod(new PasswordTransformationMethod());

        if(Config.isUserLogined()){
            mUserNameEt.setText( HXPreferenceUtils.getInstance().getCurrentUserMobile());
        }
    }

    /**
     * 发送验证码
     */
    private void sendIdentifyingCode(){
        userNameStr = mUserNameEt.getText().toString();

        if(TextUtils.isEmpty(userNameStr) ){
            Toast.makeText(this, R.string.register_mobile_error, Toast.LENGTH_SHORT).show();
            return;
        }

        if(userNameStr.length() < 11 ){
            Toast.makeText(this, R.string.register_mobile_length_error, Toast.LENGTH_SHORT).show();
            return;
        }

        SMSSDK.getVerificationCode("86",userNameStr);
        mVerificationBt.setEnabled(false);
    }
    public String userNameStr;
    public String firstPasswordStr;
    public String verficationStr;

    private void processChange(){
        // 用户注册信息提交
        userNameStr = mUserNameEt.getText().toString();
        firstPasswordStr = mPasswordEt.getText().toString();
        final String secondPasswordStr = mPasswordAgainEt.getText().toString();
        verficationStr = mVerificationEt.getText().toString();

        if(TextUtils.isEmpty(userNameStr) ){
            Toast.makeText(this, R.string.register_mobile_error, Toast.LENGTH_SHORT).show();
            return;
        }

        if(userNameStr.length() < 11 ){
            Toast.makeText(this, R.string.register_mobile_length_error, Toast.LENGTH_SHORT).show();
            return;
        }

        if(TextUtils.isEmpty(verficationStr) ){
            Toast.makeText(this, R.string.register_verification_tips, Toast.LENGTH_SHORT).show();
            return;
        }

        if(TextUtils.isEmpty(firstPasswordStr) ){
            Toast.makeText(this, R.string.login_password_empty_tips, Toast.LENGTH_SHORT).show();
            return;
        }

        if(!firstPasswordStr.equals(secondPasswordStr)){
            Toast.makeText(this, R.string.register_pwd_different_tips, Toast.LENGTH_SHORT).show();
            return;
        }
        SMSSDK.submitVerificationCode("86", userNameStr, verficationStr);

    }

    private void changePasswordServer() {
        NetHelper.userPasswordChange(PasswordForgetActivity.this, "", userNameStr, Utils.MD5(firstPasswordStr.trim()),  new NetUtils.NetCallBack<ServiceResult>() {
            @Override
            public void success(ServiceResult rspData) {
                if (rspData.getRetcode() == 0 ) {
                    Toast.makeText(PasswordForgetActivity.this, getResources().getString(R.string.password_change_ok), Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent();
                    if(Config.isUserLogined()) {
                        intent.putExtra("UserName", Config.getUserName());
                        intent.putExtra("Password", firstPasswordStr);
                    }
                    setResult(RESULT_OK, intent);
                    PasswordForgetActivity.this.finish();
                } else {
                    Toast.makeText(PasswordForgetActivity.this, rspData.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void failed(String msg) {
                Toast.makeText(PasswordForgetActivity.this, msg, Toast.LENGTH_SHORT).show();
            }
        }, ServiceResult.class);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterEventHandler(eh);
    }

    class Countdown extends CountDownTimer {
        public Countdown(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            mVerificationBt.setText(R.string.register_verification_get);
            mVerificationBt.setEnabled(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mVerificationBt.setText(String.valueOf(millisUntilFinished / 1000) );
        }
    }
}
